"""
Created on 2022-05-26
@author:刘飞
@description:增删改查的数据库操作
"""
from datetime import datetime, timedelta
from typing import Optional
from jose import jwt
from sqlalchemy.orm import Session
from passlib.context import CryptContext
from fastapi import HTTPException, status
from apps.user import models
from utils.custom_config import SECRET_KEY, ALGORITHM

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


def verify_password(plain_password: str, hashed_password: str):
    """
    验证密码
    :param plain_password:
    :param hashed_password:
    :return:
    """
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password: str):
    """
    密码加密
    :param password:
    :return:
    """
    return pwd_context.hash(password)


def get_user(db: Session, username: str):
    """
    根据用户名查询用户
    :param db:
    :param username:
    :return:
    """
    return db.query(models.User).filter(models.User.username == username).first()


def authenticate_user(db: Session, username: str, password: str):
    """
    获取用户对象
    :param db:
    :param username:
    :param password:
    :return:
    """
    user = get_user(db, username)
    if not user:
        return False
    if not verify_password(password, user.hashed_password):
        return False
    return user


def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
    """
    创建token信息
    :param data:
    :param expires_delta:
    :return:
    """
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


def create_user(db: Session, data: dict):
    """
    创建用户
    :param db:
    :param data:
    :return:
    """
    data['hashed_password'] = get_password_hash(data.get('password'))
    data.pop('password')
    db_user = models.User(**data)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


def get_user_list(db: Session, item: dict):
    """
    用户列表查询
    """
    users = db.query(models.User)
    return users


def get_user_id(db: Session, pk: int):
    """
    根据id值查询用户
    """
    user = db.query(models.User).filter_by(id=pk).first()
    return user


def user_edit(db: Session, pk: int, item: dict):
    """
    用户编辑
    """
    print(item)
    res = db.query(models.User).filter_by(id=pk).update(item)  # {'username': '利斯在', 'email': None, 'is_active': True}
    print(f'res{res}')
    db.commit()


def user_delete(db: Session, pk: int):
    """
    用户删除
    """
    db.query(models.User).filter_by(id=pk).delete()
    db.commit()
